<script setup lang="ts">
  //
  import qs from 'qs';
  import { throttle } from 'lodash-es';
  import { rightLowCodeShow } from '@/components/LeftTree';
  import { formData, formGroup, tablsType } from './index';
  import { getUnitId, getUnitUpdate } from '@/api/Unitregein';
  import { getDatalist } from '@/api/sourceData';
  import { tabsBindValues } from './index';
  import useLoading from '@/hooks/loading';
  import Table from './components/table.vue';
  const { loadingIcon, setLoading } = useLoading();
  // const pages = ref<String>('单元');
  const myform = ref<any>(null);
  const submitData = ref<Namespace.UnitObjectSaveUp>({});
  // 判断是否是顶层
  const GroupIs = ref<boolean>(false);
  const tabsValue = ref<Array<tablsType>>([]);
  const childrenId = ref<string>('');
  const numberValue = ref<number>(1);
  const activeNameChild = ref<string>();
  const oldActiveNameChild = ref<string>();
  const tableData = ref<Array<Namespace.tableData>>();

  /** 树形组件传值过来的数据 */
  const props = defineProps({
    data: {
      type: Object,
      default: () => {},
    },
    regionCode: {
      type: String,
      default: '',
    },
  });

  watch(
    props.data,
    async (value) => {
      if (value.dataId.id) {
        if (value.dataId.id == '0') {
          rightLowCodeShow.value = false;
        }
        const { data } = await getDatalist(props.data.dataId.id);
        tableData.value = data;
        tabsBindValues.value = 'sql管理';
        childrenId.value = value.dataId.id;
        if (value.dataId.icon == 'jstree-group' || value.dataId.icon == 'jstree-sqlAssign') {
          tabsValue.value = [{ value: 'sql管理', icons: 'pages' }];
        } else {
          tabsValue.value = [
            { value: 'sql管理', icons: 'pages' },
            { value: '验证sql', icons: 'table' },
          ];
        }
        GroupIs.value =
          !value.dataId.hasParent &&
          value.dataId.parentId == '0' &&
          value.dataId.icon == 'jstree-group';
        if (value.dataId.id == '0') {
          ElMessage.error('类型错误！');
          rightLowCodeShow.value = false;
        } else {
          rightLowCodeShow.value = true;
        }
        const index = tabsValue.value.findIndex((it) => {
          return it;
        });
        if (myform.value && value.dataId.id == '0') {
          myform.value[index].reset();
        }
        // unitInitial.formRules.splice(0, unitInitial.formRules.length);
        await setTimeout(() => {
          momUpdate(rightLowCodeShow.value, value.dataId.id);
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  const momUpdate = async (value: Boolean, _id: String) => {
    if (value) {
      const { data } = await getUnitId({ unitId: _id });
      if (data) {
        if (GroupIs.value) {
          formGroup.formFields = data;
        } else {
          formData.formFields = data;
        }
      } else {
        rightLowCodeShow.value = false;
      }
    }
  };
  const sendUpTreeData = inject('sendUpTree') as Function;

  const getForm = throttle(async () => {
    numberValue.value++;
    const index = tabsValue.value.findIndex((it) => {
      return it;
    });
    myform.value[index].validate();
    await setTimeout(async () => {
      setLoading(true);
      if (myform.value[index].success) {
        if (submitData.value.createDate && submitData.value.updateDate) {
          delete submitData.value.createDate;
          delete submitData.value.updateDate;
        }
        try {
          const { code } = await getUnitUpdate(qs.stringify(submitData.value));
          if (code == 0) {
            setTimeout(() => {
              sendUpTreeData({ numberValue: numberValue.value, id: props.data.dataId, code: 0 });
              setLoading(false);
            }, 500);
          }
        } catch (error) {
          setLoadingFalse();
        } finally {
          setLoadingFalse();
        }
      }
      setLoadingFalse();
    });
  }, 5000);
  const setLoadingFalse = () => {
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  const hanldFromData = async (value) => {
    submitData.value = value as Namespace.UnitObjectSaveUp;
  };

  const handleTabsChange = async (activeName, oldActiveName) => {
    activeNameChild.value = activeName;
    oldActiveNameChild.value = oldActiveName;
  };
  const handleUpdateTables = (value: Array<Namespace.tableData>) => {
    tableData.value = value;
  };
</script>

<template>
  <div class="page_content">
    <ElTabs
      type="card"
      :before-leave="handleTabsChange"
      v-model="tabsBindValues"
      v-if="rightLowCodeShow"
      class="page_content_tabs"
    >
      <ElTabPane v-for="item in tabsValue" :name="item.value" :key="item.value" :label="item.value">
        <template #label>
          <span class="custom-tabs-label">
            <SvgIcon :color="item.color" :name="item.icons" />
            <span class="page_content_titleValue">{{ item.value }}</span>
          </span>
        </template>
        <template #default>
          <div class="page_content_tablePages" v-show="item.value == 'sql管理'">
            <ElementForm
              ref="myform"
              v-if="item.value == 'sql管理'"
              :loadKey="GroupIs ? formGroup.loadKey : formData.loadKey"
              :formFields="GroupIs ? formGroup.formFields : formData.formFields"
              :formRules="GroupIs ? formGroup.formRules : formData.formRules"
              :labelWidth="110"
              @update:value="hanldFromData"
            >
              <div style="text-align: center">
                <ElButton type="primary" :loading="loadingIcon" @click="getForm()">提交</ElButton>
              </div>
            </ElementForm>
          </div>
          <div class="page_content_tableData" v-show="item.value == '验证sql'">
            <Table
              :id="props.data.dataId.id"
              :tableData="tableData"
              @update:value="handleUpdateTables"
            />
          </div>
        </template>
      </ElTabPane>
    </ElTabs>
  </div>
</template>

<style lang="scss" scoped>
  .page_content {
    &_tabs {
      height: 100vh;
      :deep(.el-tabs__nav-scroll) {
        box-sizing: border-box;
        // padding-left: 60px;
      }
    }
    &_tablePages {
      box-sizing: border-box;
      padding: 0 45px;
      margin-top: 15px;
    }
    &_titleValue {
      margin-left: 10px;
    }
    &_tableData {
      height: calc(100vh - 40px);
      box-sizing: border-box;
      padding: 0 25px;
      padding-top: 15px;
      overflow: auto;
    }
    // &_pages {
    //   height: calc(100vh - 56px);
    //   margin-top: 15px;
    // }
    // &_element {
    //   height: calc(100vh - 41px);
    // }
    // &_build {
    //   height: calc(100vh - 40px);
    //   .build {
    //     height: $height;
    //     iframe {
    //       height: $height;
    //       width: $width;
    //       border: none;
    //     }
    //   }
    // }
    :deep(.el-tabs__header) {
      margin: 0;
    }
  }
</style>
